<template>
  <div class="root">
    <el-container style="height: 500px; border: 1px solid #eee;border-radius: 10px;">
  
  <el-header style="text-align: right; font-size: 12px ; border-top-left-radius: 10px;border-top-right-radius: 10px;">
    <!-- 个人信息 -->
    <div class="block" style="float:left;margin-top: 10px;cursor: pointer;">
      <el-avatar size="large" :src="IconUrl"></el-avatar>
    </div>
    <span style="font-size:25px;display: inline-block;float: left;margin-left: 10px;cursor: pointer;">{{UserInfo.username}}</span>
    <div style="margin-right: 250px; display: inline-block; font-size: 20px;">{{currentChat}}</div>
    <el-popover
    placement="right"
    trigger="hover"
     >
    <slot>当前状态：{{aliving?"在线":"离线"}}</slot>
    <el-button slot="reference" style="background-color: rgb(201,197,191);border: none;float: left;margin-top: 15px;" :style="{color:(aliving?green:grey)}">
      <div class="alive" :class="{aliving:aliving}" ></div>&nbsp;
      {{aliving?"在线":"离线"}}
    </el-button>
  </el-popover>
  <!-- 申请信息验证 -->
  <el-dropdown >
        <i class="el-icon-s-check"  style="margin-right: 15px;width: 10px;cursor: pointer;padding: 10px 12px 8px 8px;"></i>
        <el-dropdown-menu slot="dropdown">
      
          
            <el-dropdown-item @click.native="FriendTableVisible=true">
              
              <el-badge :value=FriendApplyCount class="item" :type="FriendApplyCount==0?'primary':'warning'">
                好友
              </el-badge>
            </el-dropdown-item>
          
            <el-dropdown-item @click.native="GroupTableVisible=true">
              <el-badge :value=GroupApplyCount class="item" :type="GroupApplyCount==0?'primary':'warning'">
              群聊
            </el-badge>
            </el-dropdown-item>
          
        </el-dropdown-menu>
    </el-dropdown>
  
  <el-dialog title="好友申请" :visible.sync="FriendTableVisible" :append-to-body="true" width="400px">
  <el-table :data="ApplyRecord" >
    <el-table-column property="account" label="邀请账号" width="150"></el-table-column>
    <!-- <el-table-column property="name" label="姓名" width="150"></el-table-column> -->
    <el-table-column  label="操作">
      <template slot-scope="scope"> 
        <el-button type="primary" @click.native.prevent="FriendAgree(scope.row)">同意</el-button>
        <el-button type="danger" @click.native.prevent="FriendDisagree(scope.row)" style="margin-left: 10px;">拒绝</el-button>
      </template>
      
    </el-table-column>
  </el-table>
</el-dialog>
<el-dialog title="群聊申请" :visible.sync="GroupTableVisible" :append-to-body="true" width="500px">
  <el-table :data="ApplyRecord" >
    <el-table-column property="account" label="邀请账号" width="150"></el-table-column>
    <el-table-column  label="操作">
      <template slot-scope="scope"> 
        <el-button type="primary" @click.native.prevent="FriendAgree(scope.row)">同意</el-button>
        
        <el-button type="danger" @click.native.prevent="FriendDisagree(scope.row)" style="margin-left: 10px;">拒绝</el-button>
      </template>
    </el-table-column>
  </el-table>
</el-dialog>

    <el-dropdown >
        <i class="el-icon-setting"  style="margin-right: 15px;width: 10px;cursor: pointer;padding: 10px 12px 8px 8px;"></i>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item>关于</el-dropdown-item>
          <el-dropdown-item>退出</el-dropdown-item>
          <el-dropdown-item @click.native="addFriend">添加好友</el-dropdown-item>
          <el-dropdown-item>添加群聊</el-dropdown-item>
        </el-dropdown-menu>
    </el-dropdown>
    </el-header>
    <!-- 添加好友 -->
    <el-dialog
      title="添加好友"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="handleClose"
      :modal-append-to-body="false"
      >
      <el-form :model="form">
        <el-form-item  :label-width="formLabelWidth">
              <el-input v-model="FriendAccount" placeholder="用户账号"  style="width: 70%;margin-right: 10px;margin-left: -30px;"
            ></el-input>
            <el-button type="success" @click.native="loadAddFriend">添加</el-button>
        </el-form-item>
      </el-form>
</el-dialog>
<el-dialog
      :visible.sync="AddFriendflag"
      width="300px"
      :modal-append-to-body="false"
      >
      <span>{{AddFriendMsg}}</span>
</el-dialog>

  <el-container>
    <el-aside width="200px" style="background-color: rgb(238, 241, 246);border-bottom-left-radius: 10px;">
      <el-scrollbar style="height:483px;" class="scrollbar-for" wrap-style="overflow-x:hidden;">
    <el-menu >
      <!-- 好友列表 -->
      <el-submenu index="1">
        <template slot="title"><i class="el-icon-user-solid"></i>好友列表</template>
        <el-menu-item-group>
          <el-tooltip class="item" effect="dark"  placement="left-start" 
          v-for="list in FriendList" :key="list.username">
          <div slot="content">账号:{{list.account}}</div>
          <el-menu-item @click="ChangeCurrentChat(list.name,'friend')">
            <div class="alive" :class="{aliving:list.alive}" style="margin-right: 10px;"></div>
            {{list.name}}
          </el-menu-item>
          </el-tooltip>
        </el-menu-item-group>
      </el-submenu>
      <!-- 群聊列表 -->
      <el-submenu index="2">
        <template slot="title"><i class="el-icon-menu"></i>群聊列表</template>
        <el-menu-item-group>
          <el-popover
            placement="left-start"
            :title="list.name"
            width="100"
            trigger="hover"
            v-for="list in GroupList" :key="list.name">
            <slot>群号:{{list.account}}<br/>群成员:<br/>
              <span v-for="menber in list.member" :key="menber.username" style=" display: block;">{{menber.username}}</span></slot>
            <el-menu-item slot="reference" @click="ChangeCurrentChat(list.name,'group')">{{list.name}}</el-menu-item>
          </el-popover>
        </el-menu-item-group>
      </el-submenu>
      
    </el-menu>
  </el-scrollbar>
  </el-aside>
  <el-empty description="请选择好友或群聊进行聊天" v-show="!mainflag" style="background-color: rgb(218,208,202);width: 600px;height: 483px;"></el-empty>
    <!-- 主聊天框 -->
    <el-main style="background-color: lightgray;" v-show="mainflag">
      <!-- 聊天信息显示框 -->
      <div class="showChat" >
        <el-scrollbar style="height:100%;" class="scrollbar-for" wrap-style="overflow-x:hidden;" ref="myScrollbar">
          <div class="ChatInfo" v-for="list,index in arr" :key="index" :class="
          list.person== UserInfo.username?'selftalk':'othertalk'
        ">
        <div class="time">{{list.time}}</div>
          <div class="Info">
              <el-avatar size="medium" :src="IconUrl" 
            :style="{float:(list.person== UserInfo.username?'right':'left')}"
            style="margin:12px;"
            ></el-avatar>
          <div class="chatwords" style="display:inline-block;">
            <div class="name" style="height: 20px;font-size: 16px;">{{list.person}}</div>
            <div class="words" style="max-width:380px;"
            :style="{float:(list.person== UserInfo.username?'right':'left')}"
            >{{list.words}}</div>
            
            <el-popover
              placement="bottom"
              v-show=!list.status
              width="50"
              trigger="hover"
              content="消息发送失败">
              <!-- <el-button slot="reference">hover 激活</el-button> -->
              <div class="fail" slot="reference" style="background-color: red;width: 15px;height: 15px;
            margin: 13px;text-align: center;line-height: 15px;border-radius: 50%;color: #eee;cursor: pointer;"
            :style="{float:(list.person== UserInfo.username?'right':'left')}"
            >!</div>
            </el-popover>
          </div>

          </div>
        </div>
        </el-scrollbar>
      </div>
      <hr>
      <!-- 信息输入框 -->
      <div class="input" style="height: 130px;width:100%;">
        <div class="tools" style="height:20px;width: 550px;margin-top: -5px;">
          <i class="el-icon-picture-outline" @click="SendImg"></i>
          <i class="el-icon-camera-solid"></i>
        </div>
        <textarea style="border:0;border-radius:5px;background-color:rgba(241,241,241,.98);width: 530px;height: 95px;padding: 10px;resize: none; margin-top: 10px;" placeholder="" v-model="newWords">
        </textarea>
        <el-button type="success" class="sendInfo" @click="SendInfo" >发送</el-button>
      </div>
      <el-dialog
        title="发送图片"
        :visible.sync="ImgVisible"
        width="500px"
        :modal-append-to-body="false"
        >
        <el-scrollbar style="height: 300px;width: 300px;margin: auto;" >
          <div contenteditable="true" style="height: 200px; margin:20px auto;">
        </div>
        </el-scrollbar>
        <span slot="footer" class="dialog-footer">
          <!-- @click="SendImgInfo" -->
          <el-button type="primary"  >发 送</el-button>
        </span>
      </el-dialog>
    </el-main>
  </el-container>
</el-container>
  </div>

</template>

<script>
import axios from 'axios'
var ws = null
export default {
    name:'ChatMain',
    data() {
      return {
        UserInfo:{//用户信息
          account:'',
          username:''
        },
        FriendList:[],
        GroupList:[],
        IconUrl:'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
        arr:[],
        currentChat:'',//当前聊天好友/群聊
        to_account:'',//当前聊天好友/群聊的account
        newWords:'',//最新的聊天信息
        mainflag:false,//未选择好友或群聊时聊天页面不展示
        currentType:'',//当前选中的是好友还是群聊
        aliving:false,//用户的在线信息
        green:'green',
        grey:'grey',
        isFocus:false,
        dialogVisible: false,
        form:{
          name:''
        },
        formLabelWidth: '120px',//弹框宽度
        FriendAccount:'',//添加好友
        // userList:[
        //   {
        //     name:'123',
        //     account:'123',
        //     online:false
        //   },
        //   {
        //     name:'456',
        //     account:'456',
        //     online:true
        //   },
        //   {
        //     name:'678',
        //     account:'678',
        //     online:false
        //   },
        //   {
        //     name:'456',
        //     account:'456',
        //     online:true
        //   },
        //   {
        //     name:'678',
        //     account:'678',
        //     online:false
        //   }
        // ],
        FriendApplyCount:0,
        GroupApplyCount:0,
        // searchRecord:[
        //   {
        //     account:'123',
        //     name:'Liao'
        //   },
        //   {
        //     account:'123',
        //     name:'Liao'
        //   },
        //   {
        //     account:'123',
        //     name:'Liao'
        //   }
        // ],
        FriendTableVisible:false,
        GroupTableVisible:false,
        ImgVisible:false,
        AddFriendMsg:'',
        AddFriendflag:false,
        ApplyRecord:[]
      }
    },
    mounted() {
      // 路由设置当前用户信息
      this.UserInfo.account = this.$route.params.account;
      // this.UserInfo.username = this.$route.params.account;
      // 从store中取得FriendList数据
      // this.FriendList = this.$store.state.FrinendList
      this.GroupList = this.$store.state.GroupList
      ws = new WebSocket('ws://localhost:8081/ws')
      ws.addEventListener('open',this.handleWsOpen.bind(this),false);
      ws.addEventListener('close',this.handleWsClose.bind(this),false);
      ws.addEventListener('error',this.handleWsError.bind(this),false);
      ws.addEventListener('message',this.handleWsMessage.bind(this),false);
    },
    methods: {
      //弹框关闭调用
      handleClose(){
        console.log('dialog关闭');
        this.dialogVisible = false
      },
      //添加好友
      addFriend(){
        this.dialogVisible = true 
      },
      handleWsOpen(e){
        console.log('FE:WebSocket open',e);
        this.aliving = true
        ws.send(JSON.stringify({
          user_id:this.UserInfo.account
        }))
      },
      handleWsClose(e){
        console.log('FE:WebSocket close',e);
      },
      handleWsError(e){
        console.log('FE:WebSocket error',e);
      },
      handleWsMessage(e){
        console.log('FE:WebSocket message',e);
        var msg = JSON.parse(e.data);//收到发来的信息
        console.log(msg);
        var arr1= null
        if (msg.message=="成功发送"||msg.status=="-1") {
          //发送失败，增加自己发的信息
           arr1 = {
                person:this.UserInfo.username,//信息发送方
                words:this.newWords,
                time:new Date().getHours()+':'+new Date().getMinutes(),
                status:msg.status=="-1"?false:true
              }
        this.arr.push(arr1)
        }else if (msg.user_id!=null) {
          this.UserInfo.username = msg.personal_name
          //获取好友列表
          //获取好友账号列表
          var accountList = Object.keys(msg.friends)
          //获取好友名称列表
          var nameList  = Object.values(msg.friends)
          //将好友信息加到FriendList
          var tempFriend = null
          for (let i = 0; i < accountList.length; i++) {
              tempFriend = {
              account:accountList[i],
              name:nameList[i],
              ChatInfo:[],
              alive:false
            }
            this.FriendList.push(tempFriend)
            tempFriend = null
          }
        }else if (msg.from_account=='SystemFriend') {
          //好友验证信息
          console.log('SystemFriend');
          var ApplyInfo = {
            account:msg.message
          }
          this.ApplyRecord.push(ApplyInfo)
          this.FriendApplyCount = this.ApplyRecord.length
        }else{
          //接收好友发来的信息
          console.log(msg.message,"username1");
          var tempName=null
          for (let i = 0; i < this.FriendList.length; i++) {
            if (this.FriendList[i].account==msg.from_account) {
              tempName = this.FriendList[i].name
            }
          }
          arr1 = {
            person:tempName,//信息发送方
            words:msg.message,
            time:new Date().getHours()+':'+new Date().getMinutes(),
            status:msg.status=="-1"?false:true
          }
        }
        // 接收到信息存储到FriendList相应的列表
        for (let index = 0; index < this.FriendList.length; index++) {
          if (this.FriendList[index].account==msg.from_account) {
            this.FriendList[index].ChatInfo.push(arr1)
            this.arr = this.FriendList[index].ChatInfo
          }
        }
        this.newWords=''
        
      },
      // handleSend(){
      //   ws.send(JSON.stringify({
      //     from_account:this.UserInfo.account,
      //     to_account:this.to_account
      //   }))
      // },
      // 设置所选好友的聊天记录
      ChangeCurrentChat(name,type){
        this.currentChat = name
        this.mainflag = true
        this.currentType = type
        if (type=='friend') {
          for (let index = 0; index < this.FriendList.length; index++) {
          if (this.FriendList[index].name == name) {
            this.arr = this.FriendList[index].ChatInfo
            this.to_account = this.FriendList[index].account
          }
        }
        }else if (type=='group') {
          for (let index = 0; index < this.GroupList.length; index++) {
          if (this.GroupList[index].name == name) {
            this.arr = this.GroupList[index].ChatInfo
            this.to_account = this.GroupList[index].account
          }
        }
        }
      },
      // 滚动条滑到底部函数
      ToBottom(){
        this.$nextTick(() => {
            this.$refs['myScrollbar'].wrap.scrollTop = this.$refs['myScrollbar'].wrap.scrollHeight
          })
      },
      SendInfo(){
        if (this.newWords.trim()) {
        //   let Info={
        //   person: this.UserInfo.username,
        //   words: this.newWords,
        //   time: new Date().getHours()+':'+new Date().getMinutes()
        // }
        ws.send(JSON.stringify({
          "from_account":this.UserInfo.account,
          "to_account":this.to_account,
          "message":this.newWords
        }))
        }
      },
      // 根据account更改状态
      ChangeAlive(account){
        for (let index = 0; index < this.FriendList.length; index++) {
          if (this.FriendList[index].account == account) {
            this.FriendList[index].alive = !this.FriendList[index].alive
          }
        }
      },
      search(){
        console.log('FriendName',this.FriendName);
        // var data = {
        //   name:this.FriendName
        // }
        //搜索
      },
      addFriend2(user){
        console.log(user);
      },
      FriendAgree(row){
        console.log('FriendAgree',row);
        ws.send(JSON.stringify({
          from_account:this.UserInfo.account,
          to_account:row.account,
          message:"YES"
        }))
      },
      FriendDisagree(row){
        console.log('FriendDisagree',row);
        ws.send(JSON.stringify({
          from_account:this.UserInfo.account,
          to_account:row.account,
          message:"NO"
        }))
      },
      //文本域粘贴图片
      SendImg(){
        this.ImgVisible = true
      },
      loadAddFriend(){
        var data = {
          "user_id":this.UserInfo.account,
          "goal_id":this.FriendAccount
        }
        var json = JSON.stringify(data)
        console.log(data);
        axios.post('/add_friend',json ,{
                            headers: {
                                'Content-Type':'application/json; charset=UTF-8;'
                            }
                        }
                ).then(res =>{
                var result = res.data
                console.log(res);
                this.AddFriendMsg=result.message
                this.AddFriendflag = true
            }).catch(err=>{
              console.log(err);
              console.log('添加失败err');
          })
      },
    },
    watch:{
      arr:'ToBottom',
      deep:true,
    },
    computed: {
      isSearch() {
        return this.isFocus;
    }
  }

}
</script>

<style scoped >
.root{
    width: 800px;
    height: 560px;
    position: absolute;
		left: 50%;top:50%;
		margin-top: -280px;
    margin-left: -400px;
    border-radius: 10px;
    opacity: 0.7;
}

  .el-header {
    /* background-color: #B3C0D1; */
    background-color: rgb(192,197,195);
    color: #333;
    line-height: 60px;
  }
  
  .el-aside {
    color: #333;
  }
  .ChatInfo{
    width:100%;
    margin-bottom: 10px;
  }
.selftalk{
  text-align: right;
}
.words{
  background-color: rgb(255,255,255);
  border-radius: 5px;
  padding: 4px;
  margin-top: 5px;
}
.showChat{
  height: 300px;
  width:100%;
  /* overflow: auto; */
  
}

.time{
  height: 10px;
  width: 100%;
  text-align: center;
  line-height: 10px;
  font-size: 12px;
}
i{
  width: 15px;
  height: 15px;
  margin-left: 10px;
  cursor: pointer;
  padding: 7px;
  border-radius: 4px;
}
i:hover{
  background-color: rgb(241,241,241);
}
.sendInfo{
  position: absolute;
  top: 490px;
  left: 685px;
}
.alive{
  width:8px;
  height: 8px;
  border-radius: 50%;
  background: grey;
  display: inline-block;
}
.aliving{
  background-color: lightgreen;
}
.el-dropdown-link{
  cursor: pointer;
}
.el-dropdown-link:hover{
  color: rgb(145,213,255);
}
.item {
  margin-top: 10px;
}

</style>